package com.mao.security;

import com.mao.utils.R;
import com.mao.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager,RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
    }



    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // 从header 中获取token
        String token = request.getHeader("token");

        // token 不为空 移除token 从redis中删除token

        if (token != null || token.equals("")){
            // 移除token
            tokenManager.removerToken(token);

            // 从token获取用户名
            String username = tokenManager.getUserInfoToken(token);
            redisTemplate.delete(username);
        }

        ResponseUtil.out(response, R.ok());
    }
}
